//H5处理事件
function plusReady() {
	plus.webview.currentWebview().setStyle({
		scrollIndicator: 'none'
	});
	// 是否支持状态栏
	var isImmersedStatusbar = plus.navigator.isImmersedStatusbar();
	// 如果支持则获取状态栏高度，将header元素上填充值重新赋值
	if(isImmersedStatusbar) {
		var StatusbarHeight = plus.navigator.getStatusbarHeight(),
			header = document.getElementsByTagName("header")[0];
// 		if(header) {
// 			header.style.paddingTop = StatusbarHeight + "px";
// 		};
	};
};
if(window.plus) {
	plusReady();
} else {
	document.addEventListener('plusready', plusReady, false);
};

var BASE = {
	//手机号正则
	phone_test: /^1[3|4|5|6|7|8|9][0-9]{9}$/,
	//打开新窗口判断值
	openWin_boolean: true,
	//打开窗口后恢复openWin_boolean值
	Rest_openWinBoolean: function() {
		BASE.openWin_boolean = false;
		setTimeout(function() {
			BASE.openWin_boolean = true;
		}, 1000)
	},
	//打开原生状态栏新窗口
	//打开新窗口
	Default_window: function(url, WId, title, type, data){
		if(localStorage.getItem('network-status') === 'false'){
			mui.toast('当前暂无网络~');
			return false
		};
		if(!data) data = {};
		var webview_style = {
			left: 0,
			right: 0,
			top: 0,
			bottom: 0,
			position: 'static',
			popGesture: "close"
		};
		webview_style.titleNView = {
			type: type,
			autoBackButton: true,
			titleText: title,
			titleColor: '#FFFFFF',
			backgroundColor: "#31cdbf"
		};
		var webview = plus.webview.create(url, WId, webview_style, data);
		plus.webview.show(webview, "slide-in-right", 300);
    },
	Custom_window: function(url, WId, data, type) {
		if(localStorage.getItem('network-status') === 'false'){
			mui.toast('当前暂无网络~');
			return false
		};
		if(!data) data = {};
		if(!type) type = 'slide-in-right';
		mui.openWindow({
			url: url,
			id: WId,
			extras: data,
			show: {
				autoShow: true,
				aniShow: type,
			}
		});
	},
	//支付
	Payment: function (api, pay_type, order_id, success_fun, error_fun) {
		// 获取支付通道
		var pays = {},
			is_pay = null,//是否为支付状态
			PAYSERVER = BASE.Host + api + '?payid=';
		plus.payment.getChannels(function(channels) {
			for(var i in channels) {
				var channel = channels[i];
				pays[channel.id] = channel;
			}
			// 检测是否安装支付服务,如果当前支付方式未安装，则提示安装
			if(!pays[pay_type].serviceReady) {
				var txt = '';
				switch(pays[pay_type].id) {
					case 'alipay':
						txt = '检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？';
						break;
					default:
						txt = '系统未安装“' + pays[pay_type].description + '”服务，无法完成支付，是否立即安装？';
						break;
				};
				plus.nativeUI.confirm(txt, function(e) {
					if(parseInt(e.index) === 0) {
						pays[pay_type].installService();
					};
				}, pays[pay_type].description);
				return false;
			}else{
				//如果安装当前支付方式，执行以下方法
				if(is_pay) {
					return;
				}; //检查是否请求订单中
				var host = PAYSERVER;
				if(pay_type === 'alipay' || pay_type === 'wxpay') {
					host += pay_type + '&oid=' + order_id;
				} else {
					mui.toast('当前环境不支持此支付通道');
					return;
				};
				var appid = plus.runtime.appid;
				if(navigator.userAgent.indexOf('StreamApp') >= 0) {
					appid = 'Stream';
				};
				host += '&appid=' + appid;
				is_pay = plus.nativeUI.showWaiting();
				// 请求支付订单
				var xhr = new XMLHttpRequest();
				xhr.onreadystatechange = function() {
					switch(xhr.readyState) {
						case 4:
							is_pay.close();
							is_pay = null;
							if(parseInt(xhr.status) === 200) {
								var order = xhr.responseText;
								plus.payment.request(pays[pay_type], order, function(result) {
									success_fun();
								}, function(event) {
									alert('支付失败！');
//									alert('支付失败：' + event.code + event.message);
									error_fun();
								});
							} else {
								mui.toast('请求订单失败：' + xhr.status);
							}
							break;
						default:
							break;
					}
				};
				xhr.open('POST', host);
				xhr.send();
			}
		}, function(e) {
			mui.toast('获取支付通道失败：' + e.message);
		});
	},
	//获取字符创参数
	Get_parameter: function (str, name) {
        str = str.split("?")[1].split("&");
        var ret = {};
        str.forEach(function(obj) {
        	var d = obj.split("=");
            ret[d[0]] = decodeURI(d[1]);
        });
        return ret[name];
    },
	//获取状态栏高度
	StatusbarHeight: function() {
		var height = 0,
			isImmersedStatusbar = plus.navigator.isImmersedStatusbar();
		if(isImmersedStatusbar) {
			height = plus.navigator.getStatusbarHeight();
		};
		return height;
	},
	ultZeroize: function(v, l){
		var z = "";
		l = l || 2;
		v = String(v);
		for(var i=0; i<l-v.length; i++){
			z += "0";
		};
		return z + v;
	},
	//格式化日期时间字符串，格式为"YYYY-MM-DD HH:MM:SS"
	dateToStr: function(d){
		//BASE.dateToStr(new Date());
		return (
			d.getFullYear()
			+ "-"
			+ BASE.ultZeroize(d.getMonth() + 1)
			+ "-"
			+ BASE.ultZeroize(d.getDate())
			+ " "
			+ BASE.ultZeroize(d.getHours())
			+ ":"
			+ BASE.ultZeroize(d.getMinutes())
			+ ":"
			+ BASE.ultZeroize(d.getSeconds())
		)
	},
	//格式化时长字符串，格式为"HH:MM:SS"
	timeToStr: function(ts){
		//BASE.timeToStr(360);
		if(isNaN(ts)){
			return "--:--:--";
		}
		var h = parseInt(ts / 3600),
			m = parseInt((ts % 3600) / 60),
			s = parseInt(ts % 60);
		return (
			BASE.ultZeroize(h)
			+ ":"
			+ BASE.ultZeroize(m)
			+ ":"
			+ BASE.ultZeroize(s)
		)
	}
};
// 打开原生状态栏窗口
// if(BASE.openWin_boolean){
// 	BASE.Rest_openWinBoolean();
// 	BASE.Open_window('set.html', 'set.html', '账户设置', "default")
// }
// 打开自定义窗口（{}可不传）
// BASE.Custom_window('set.html', 'set.html', {})
//
// mui.toast('message');
//
// plus.nativeUI.showWaiting();
// plus.nativeUI.closeWaiting();
//
// 改变状态栏颜色
// plus.navigator.setStatusBarStyle('light');/dark
//
//
// 获取当前窗口
// plus.webview.currentWebview();
// 获取指定窗口
// plus.webview.getWebviewById('a.html');
// 关闭窗口
// plus.webview.close(a);
//
//判断当前网络状态
// get_connection();
// function get_connection() {
//  var types = {};
//  types[plus.networkinfo.CONNECTION_UNKNOW] = "Unknown connection";
//  types[plus.networkinfo.CONNECTION_NONE] = "None connection";
//  types[plus.networkinfo.CONNECTION_ETHERNET] = "Ethernet connection";
//  types[plus.networkinfo.CONNECTION_WIFI] = "WiFi connection";
//  types[plus.networkinfo.CONNECTION_CELL2G] = "Cellular 2G connection";
//  types[plus.networkinfo.CONNECTION_CELL3G] = "Cellular 3G connection";
//  types[plus.networkinfo.CONNECTION_CELL4G] = "Cellular 4G connection";
//  if(types[plus.networkinfo.getCurrentType()] === "None connection" || types[plus.networkinfo.getCurrentType()] === "Unknown connection") {
//   localStorage.setItem('network-status', 'false')
//  } else {
//   localStorage.setItem('network-status', 'true')
//  }
// };
//
// document.addEventListener("resume", function() {
//  get_connection()
// }, false);
//
// document.addEventListener("netchange", function() {
//  var nt = plus.networkinfo.getCurrentType();
//  switch(nt) {
//   case plus.networkinfo.CONNECTION_ETHERNET:
//   case plus.networkinfo.CONNECTION_WIFI:
//    localStorage.setItem('network-status', 'true');
//    mui.toast('您已切换至无线网络');
//    break;
//   case plus.networkinfo.CONNECTION_CELL2G:
//   case plus.networkinfo.CONNECTION_CELL3G:
//   case plus.networkinfo.CONNECTION_CELL4G:
//    localStorage.setItem('network-status', 'true');
//    mui.toast('您已切换至移动网络');
//    break;
//   default:
//    localStorage.setItem('network-status', 'false');
//    mui.toast('您已关闭网络');
//    break;
//  }
// }, false);
